package com.ruoyi.project.app.util;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class EncodeUtils {
    private static char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public EncodeUtils() {
    }

    public static byte[] encodeHmacSha256(String secret, String data) {
        try {
            PBEKeySpec keySpec = new PBEKeySpec(secret.toCharArray());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFactory.generateSecret(keySpec);
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(key);
            return mac.doFinal(data.getBytes());
        } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException var6) {
            throw new RuntimeException(var6);
        }
    }

    public static String encodeSha1Hex(String data) {
        try {
            return encodeBy(data, MessageDigestType.SHA1);
        } catch (NoSuchAlgorithmException var2) {
            return null;
        }
    }

    public static String encodeMd5Hex(String data) {
        try {
            return encodeBy(data, MessageDigestType.MD5);
        } catch (NoSuchAlgorithmException var2) {
            return null;
        }
    }

    public static String encodeBy(String encodedString, MessageDigestType encodeType) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance(encodeType.getName());
        byte[] digest = md5.digest(encodedString.getBytes(StandardCharsets.UTF_8));
        return toHex(digest);
    }

    public static String encodeBase64String(byte[] data) {
        return new String(Base64.getEncoder().encode(data));
    }

    public static String toHex(byte[] bytes) {
        char[] str = new char[bytes.length * 2];
        int k = 0;
        byte[] var3 = bytes;
        int var4 = bytes.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            byte b = var3[var5];
            str[k++] = hexDigits[b >>> 4 & 15];
            str[k++] = hexDigits[b & 15];
        }

        return new String(str);
    }

    public static enum MessageDigestType {
        MD2("MD2"),
        MD5("MD5"),
        SHA1("SHA-1"),
        SHA256("SHA-256"),
        SHA384("SHA-384"),
        SHA512("SHA-512");

        String name;

        private MessageDigestType(String name) {
            this.name = name;
        }

        public String getName() {
            return this.name;
        }
    }
}